package com.threeti.mecool.framework.dao;

import static org.hibernate.criterion.Restrictions.eq;
import static org.springframework.util.CollectionUtils.isEmpty;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;

import com.threeti.mecool.framework.domain.AbstractCustomKeyDomainEntity;

/**
 * @author Jay Meng
 **/
public abstract class AbstractCustomKeyDao<CUSTOM_ID extends Serializable, T extends AbstractCustomKeyDomainEntity> 
  extends AbstractDao<T> implements GenericCustomKeyDao<CUSTOM_ID, T>{

  public AbstractCustomKeyDao(SessionFactory sessionFactory) {
    super(sessionFactory);
  }

  @Override
	protected DetachedCriteria buildDefaultCriteria() {
		return null;
	}

	@Override
  public T loadBy(CUSTOM_ID customId) {
    return loadByCK(customId, buildDefaultCriteria());
  }

  @Override
  public void removeBy(CUSTOM_ID customId) {
    getHibernateTemplate().delete(loadBy(customId));
  }
  
  protected final T loadByCK(Serializable pkOrCk, DetachedCriteria criteria) {
    criteria.add(eq("customId", pkOrCk));

    List<T> entites = this.getHibernateTemplate().findByCriteria(criteria);
    if(!isEmpty(entites)) return entites.get(0);
    return null;
  }

}
